const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const utils = require('../../utils.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    memberDTOs: [],
    selectValue: [],
    selectMemberList:[],
    content:'',
    ciId:'',
    cgId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      ciId: options.ciId
    })

    this.obtainClassMembers(options.ciId)
  },
  
  // 获取成员列表
  obtainClassMembers(id) {
    utils.ajaxFn({
      url: config.service.obtainClassMembers,
      body: { 'ciId': id },
      callback: (data) => {
        if (data.memberDTOs.length < 1) {
          wx.showModal({
            title: '提示',
            content: "当前班级没有成员，请添加！"
          })

          return false;
        }

        this.setData({
          memberDTOs: data.memberDTOs
        })
      }
    })
  },

  // 删除成员
  deleteManage(e){
    let dataset = e.currentTarget.dataset
    let selectValue = this.data.selectValue
    let memberDTOs = this.data.memberDTOs
    selectValue.splice(dataset.index, 1)
    
    this.setData({
      selectValue: selectValue
    })


    memberDTOs.forEach(value => {
      if (value.cmId === dataset.cmid) {
        value.state = false
      } 
    })
    
    this.setData({
      memberDTOs: memberDTOs
    })

    console.log(this.data.memberDTOs)
  },

  // 选择成员
  checkboxChange(e) {
    let iarr = []
    this.data.memberDTOs.forEach(value => {
      if (e.detail.value.indexOf(''+value.uId) > -1) {
        value.state = true
        iarr.push(value)
      } else {
        value.state = false
      }
     })

    this.setData({
      selectValue: iarr
    })

    this.setData({
      selectMemberList: e.detail.value
    })
  },

  // 新建群组
  newGroup() {
    if (this.data.content == '') {
      wx.showToast({
        title: '群组名称不能为空！',
        duration: 2000
      })

      return false;
    }
    utils.ajaxFn({
      url: config.service.newGroup,
      body: {
        name:this.data.content,
        ciId: this.data.ciId
      },
      callback: (data) => {
        this.setData({
          cgId: data.cgId
        })

        this.assignGroupMembers()
      }
    })
  },

  // 指定群组成员
  assignGroupMembers(){
    utils.ajaxFn({
      url: config.service.assignGroupMembers,
      body: {
        cgId: this.data.cgId,
        uIdsJn: `[${this.data.selectMemberList}]`
      },
      callback: (data) => {
        wx.navigateTo({
          url: `/pages/groupManager/groupManager`
        })

        // wx.navigateBack({
        //   delta: 1
        // })
      }
    })
  },
  
  //群组标题
  bindKeyInput(e) {
    this.setData({
      content: e.detail.value
    })
  },
})